package com.example.javadynamiccompile.dynamic;

import java.lang.reflect.*;


/**
 * @author 陳樂
 * @version 1.0.0
 * @ClassName DynamicProxy.java
 * @Description TODO
 * @createTime 2023年03月29日 22:53:00
 */
public class DynamicProxy implements InvocationHandler {

    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("After method " + method.getName());
        return result;
    }

    public static void main(String[] args) {
        // 创建被代理对象
        RealObject realObject = new RealObject();

        // 创建代理对象
        DynamicProxy proxy = new DynamicProxy(realObject);
        Interface proxyObject = (Interface) Proxy.newProxyInstance(
                Interface.class.getClassLoader(),
                new Class<?>[] { Interface.class },
                proxy);

        // 调用代理对象的方法
        proxyObject.doSomething();
    }
}
